import { Component, OnInit, OnDestroy, Input, Output, EventEmitter } from '@angular/core';
import { ReplaySubject } from "rxjs/ReplaySubject";
import { Observable } from "rxjs/Observable";
import { Subscription } from "rxjs/Subscription";
import { HsClientService } from "./../hs-client.service";
import "rxjs/add/operator/switchMap";

@Component({
  selector: 'vtrade-summary',
  templateUrl: 'vtradesummary.component.html',
  styleUrls: ['vtradesummary.component.less']
})
export class VtradeSummaryComponent implements OnInit, OnDestroy {
  summaryList: Array<any> = [{
    //   key: "phone",
    //   label: "账户手机号",
    //   value: ""
    // }, {
    key: "account",
    label: "交易账户",
    value: ""
  }, {
    key: "account_type",
    label: "账户性质",
    value: "模拟交易"
  }, {
    key: "asset_balance",
    label: "资产值",
    value: ""
  }, {
    key: "current_balance",
    label: "当前余额",
    value: ""
  }, {
    key: "market_value",
    label: "证券市值",
    value: ""
  }, {
    key: "fetch_balance",
    label: "可取资金",
    value: ""
  }, {
    key: "enable_balance",
    label: "可用资金",
    value: ""
  }, {
    key: "frozen_balance",
    label: "冻结资金",
    value: ""
    // }, {
    //   key: "unfrozen_balance",
    //   label: "解冻资金",
    //   value: ""
    // }, {
    //   key: "fund_balance",
    //   label: "总资金余额",
    //   value: ""
    // }, {
    //   key: "today_profit",
    //   label: "*今日盈亏",
    //   value: "today_profit"
  }];
  // @Input() stockSource: ReplaySubject<any>;
  @Input() stockSource: Observable<any>;
  @Output() summarySource = new EventEmitter();
  dataSource: Observable<any>;
  dataSubscription: Subscription;
  constructor(private hsClient: HsClientService) { }

  ngOnInit() {
    this.stockSource.subscribe(res => {
      console.debug('summary stock source: ', res);
    });
    this.dataSubscription = Observable
      .merge(this.stockSource, this.hsClient.broadcast)  // 提交成功委托单之后更新summary信息
      .switchMap(() => this.hsClient.queryBalanceFast())
      .subscribe(resArr => {
        let res = Object.assign({}, resArr[0], this.hsClient.userToken);
        console.debug("summary details: ", res);
        // 给terminal计算available amount
        this.summarySource.next(res);

        // 显示的detail
        this.summaryList.map(item => {
          item.value = res[item.key] ? res[item.key] : item.value;
        });
      }, err => {
        this.summaryList.map(item => {
          item.value = "--";
        });
        console.warn('vtrade summary err: ', err);
      });
  }

  ngOnDestroy() {
    this.dataSubscription ? this.dataSubscription.unsubscribe() : null;
  }
}